import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controllers/device_list_controller.dart';
import '../widgets/device_card.dart'; // 需要创建这个Widget
import '../../../constants/enums/app_status.dart';
import '../../../shared/widgets/misc/loading_indicator.dart';
import '../../../shared/widgets/misc/empty_state.dart';
import '../../../shared/widgets/misc/error_state.dart';

/// 设备列表页面视图
class DeviceListPage extends StatefulWidget {
  const DeviceListPage({Key? key}) : super(key: key);

  @override
  State<DeviceListPage> createState() => _DeviceListPageState();
}

class _DeviceListPageState extends State<DeviceListPage> {
  final DeviceListController controller = Get.find<DeviceListController>();
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    // 监听滚动，实现加载更多
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >= _scrollController.position.maxScrollExtent * 0.9 &&
        controller.status.value != AppStatus.loadingMore &&
        controller.hasMoreData) {
      controller.loadMoreDevices();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的设备'),
        actions: [
          IconButton(
            icon: const Icon(Icons.filter_list),
            tooltip: '筛选',
            onPressed: _showFilterDialog,
          ),
          IconButton(
            icon: const Icon(Icons.add),
            tooltip: '添加设备',
            onPressed: controller.navigateToAddDevice,
          ),
        ],
        bottom: _buildSearchBar(),
      ),
      body: RefreshIndicator(
        onRefresh: controller.refreshDevices,
        child: Obx(() => _buildContent()),
      ),
    );
  }

  /// 构建搜索栏
  PreferredSizeWidget _buildSearchBar() {
    return PreferredSize(
      preferredSize: const Size.fromHeight(kToolbarHeight),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
        child: TextField(
          controller: controller.searchController,
          decoration: InputDecoration(
            hintText: '搜索设备名称或位置...',
            prefixIcon: const Icon(Icons.search),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(30.0),
              borderSide: BorderSide.none,
            ),
            filled: true,
            fillColor: Theme.of(context).scaffoldBackgroundColor,
            contentPadding: const EdgeInsets.symmetric(vertical: 0),
            suffixIcon: Obx(() => controller.searchController.text.isNotEmpty
                ? IconButton(
                    icon: const Icon(Icons.clear),
                    onPressed: () {
                      controller.searchController.clear();
                      controller.searchDevices();
                    },
                  )
                : const SizedBox.shrink()),
          ),
          onSubmitted: (_) => controller.searchDevices(), // 回车键触发搜索
        ),
      ),
    );
  }

  /// 构建页面内容
  Widget _buildContent() {
    switch (controller.status.value) {
      case AppStatus.loading:
        return const Center(child: LoadingIndicator());
      case AppStatus.error:
        return Center(
          child: ErrorState(
            message: '加载设备失败，请稍后重试。', 
            onRetry: controller.refreshDevices,
          )
        );
      case AppStatus.empty:
        return Center(
          child: EmptyState(
            message: '暂无设备，点击右上角添加设备吧！',
            onRefresh: controller.refreshDevices,
          )
        );
      case AppStatus.success:
      case AppStatus.loadingMore: // 加载更多时仍显示列表
        return _buildDeviceList();
      default:
        return const SizedBox.shrink();
    }
  }

  /// 构建设备列表
  Widget _buildDeviceList() {
    return ListView.builder(
      controller: _scrollController,
      padding: const EdgeInsets.all(8.0),
      itemCount: controller.devices.length + (controller.hasMoreData ? 1 : 0),
      itemBuilder: (context, index) {
        if (index == controller.devices.length) {
          // 列表末尾显示加载更多指示器
          return controller.status.value == AppStatus.loadingMore
              ? const Padding(
                  padding: EdgeInsets.all(16.0),
                  child: Center(child: LoadingIndicator(size: 24)),
                )
              : const SizedBox.shrink();
        }
        
        final device = controller.devices[index];
        return DeviceCard(
          device: device,
          onTap: () => controller.navigateToDeviceDetail(device.id),
          // 可以添加其他交互，如长按、滑动等
        );
      },
    );
  }
  
  /// 显示筛选对话框 (示例)
  void _showFilterDialog() {
    // 这里可以实现一个更复杂的筛选对话框
    // 允许用户选择状态和类型
    Get.dialog(
      AlertDialog(
        title: const Text('筛选设备'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 状态筛选 (示例: 下拉框)
            Obx(() => DropdownButton<String?>(
              value: controller.filterStatus?.value,
              hint: const Text('按状态筛选'),
              isExpanded: true,
              items: ['在线', '离线', '故障'] // 实际应从DeviceStatus枚举生成
                  .map((status) => DropdownMenuItem(
                        value: status,
                        child: Text(status),
                      ))
                  .toList()
                ..insert(0, const DropdownMenuItem(value: null, child: Text('所有状态'))),
              onChanged: (value) => controller.filterStatus?.value = value,
            )),
            const SizedBox(height: 10),
            // 类型筛选 (示例: 下拉框)
            Obx(() => DropdownButton<String?>(
              value: controller.filterType?.value,
              hint: const Text('按类型筛选'),
              isExpanded: true,
              items: ['传感器', '控制器', '网关'] // 实际应从DeviceType枚举生成
                  .map((type) => DropdownMenuItem(
                        value: type,
                        child: Text(type),
                      ))
                  .toList()
                 ..insert(0, const DropdownMenuItem(value: null, child: Text('所有类型'))),
              onChanged: (value) => controller.filterType?.value = value,
            )),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              controller.clearFilters();
              Get.back();
            },
            child: const Text('清除'),
          ),
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              controller.applyFilters();
              Get.back();
            },
            child: const Text('应用'),
          ),
        ],
      ),
    );
  }
} 